<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" @click="getVersion"> 获取版本 </el-button>
      <el-button v-loading.fullscreen.lock="isUpdate" class="filter-item" type="success" @click="onUpdate"> 开始升级 </el-button>
      <el-progress :text-inside="true" :stroke-width="24" :percentage="updatePercentage" status="success" />
    </div>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>版本信息</span>
          </div>
          <h3 style="margin-bottom:20px;"> 当前设备固件版本：{{ version }} </h3>
          <el-upload
            class="upload-demo"
            drag
            action="api/upload/bin"
            :file-list="fileList"
            :limit="1"
            accept=".bin"
            :on-change="handleChange"
            :on-success="handleUploadSuccess"
            multiple
          >
            <i class="el-icon-upload" />
            <div class="el-upload__text">将升级文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传bin文件，且不超过500kb</div>
          </el-upload>

        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>基本信息</span>
          </div>
          <el-form :model="device" label-position="left">
            <el-form-item label="名称:" :label-width="formLabelWidth">
              <span> {{ device.name }} </span>
            </el-form-item>
            <el-form-item label="位置:" :label-width="formLabelWidth">
              <span> {{ device.position }} </span>
            </el-form-item>
            <el-form-item label="SN:" :label-width="formLabelWidth">
              <span> {{ device.sn }} </span>
            </el-form-item>
            <el-form-item label="型号:" :label-width="formLabelWidth">
              <span> {{ device.model }} </span>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import { CMD_SWITCH } from '@/utils/cmd'

export default {
  name: 'Update',
  components: { },
  data() {
    return {
      mqttLog: [],
      device: null,
      formLabelWidth: '80px',
      version: '',
      dialogUpdateFormVisible: false,
      fileUrl: '',
      fileList: [],
      isUpdate: false,
      updateTimeoutCnt: 0,
      updatePercentage: 0
    }
  },
  created() {
    this.device = this.$route.query
    this.subscribe(this.device.pub)
    this.getVersion()
  },
  methods: {
    onUpdate() {
      console.log(this.fileList)
      if (this.fileList.length === 0) {
        this.$message({
          showClose: true,
          message: '升级错误，请先上传文件',
          type: 'error'
        })
        return
      }
      const payload = {
        code: CMD_SWITCH.set_update.toString(),
        msg: this.fileUrl
      }
      console.log(payload)
      this.publish(this.device.sub, JSON.stringify(payload))
      this.timer = setTimeout(this.resonseTimer, 3000)
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    handleUploadSuccess(response, file, fileList) {
      console.log(response)
      if (response.code === 200) {
        this.$message({ message: '上传成功~', type: 'success' })
        file.name = response.data.file_name
        this.fileUrl = response.data.file_url
      }
    },
    getVersion() {
      this.version = ''
      this.publish(this.device.sub, JSON.stringify({ code: CMD_SWITCH.get_version.toString() }))
    },
    resonseTimer() {
      if (!this.isUpdate) {
        this.$message({
          message: '设备无响应，请检查设备是否在线~',
          type: 'error'
        })
      }
    },
    updateStart() {
      this.isUpdate = true
      this.updatePercentage = 0
      this.updateTimeoutCnt = 0
      this.timer = setInterval(this.updateTimer, 1000)
    },
    updateTimer() {
      if (this.updatePercentage <= 78) {
        this.updatePercentage += 2
      }
      this.updateTimeoutCnt += 1
      if (this.updateTimeoutCnt >= 100) {
        this.updateFailed()
      }
    },
    updateDone() {
      this.updatePercentage = 100
      this.updateTimeoutCnt = 0
      this.isUpdate = false
      this.$message({
        message: '设备升级成功~',
        type: 'success'
      })
      clearInterval(this.timer)
    },
    updateFailed() {
      this.updatePercentage = 0
      this.updateTimeoutCnt = 0
      this.isUpdate = false
      this.$message({
        message: '设备升级超时，请检查网络连接~',
        type: 'error'
      })
      clearInterval(this.timer)
    },
    subscribe(val) {
      console.log('订阅')
      console.log('topic:' + val)
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      console.log('推送消息')
      console.log('topic:' + topic)
      console.log('message:' + message)
      this.$mqtt.publish(topic, message)
    }
  },
  mqtt: {
    '#'(data, topic) {
      console.log('收到消息')
      console.log('topic:' + topic)
      console.log('payload: ' + String.fromCharCode.apply(null, data))
      // var patt = /^fsc\/(rg[0-9]{0,10})\/([0-9a-zA-Z]{0,32})\/tx$/
      // var res = patt.exec(topic)
      // console.log(res)
      if (topic === this.device.pub) {
        var payload = JSON.parse(data)
        var code = parseInt(payload.aswcode)
        console.log(payload)
        console.log('主题正确')

        if (code === CMD_SWITCH.get_version) {
          this.version = payload.aswmsg
          if (this.isUpdate) {
            this.updateDone()
            console.log('升级完成')
          }
        }
        if (code === CMD_SWITCH.set_update) {
          if (payload.aswmsg === '1') {
            this.updateStart()
            console.log('升级开始')
          }
        }
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.el-row {
margin-bottom: 20px;
&:last-child {
    margin-bottom: 0;
}
}
.el-col {
border-radius: 4px;
}
.el-tag + .el-tag {
margin-left: 10px;
}
</style>
